﻿using System;
using System.Text;

namespace MySqlManager
{
    /// <summary>
    /// Layer class over a MySqlCommand used to update data to a MySQL database table
    /// </summary>
    public class MySqlUpdate : SqlQuery, IDisposable
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MySqlUpdate"/> class
        /// </summary>
        public MySqlUpdate() : base()
        {
            this.executeDelegate = this.ExecuteNonQuery;
        }

        /// <summary>
        /// Updates a column in the table
        /// </summary>
        /// <param name="column">Name of the column that will be updated</param>
        /// <param name="value">Value that will be updated in the selected column</param>
        public MySqlUpdate Set(string column, object value)
        {
            this.AddParameter(column, value);
            return this;
        }

        /// <summary>
        /// Release all resources used by the MySqlInsert
        /// </summary>
        public void Dispose()
        {
            this.Dispose(true);
        }

        /// <summary>
        /// Release the resources used by the MySqlInsert
        /// </summary>
        /// <param name="disposeNative">true if native objects should be disposed</param>
        private void Dispose(bool disposeNative)
        {
            if (disposeNative)
            {
                //dispose any native objects here
            }
            this.mySqlCommand.Dispose();
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Method called by the SQLQuery base methods Execute and BeginExecute
        /// </summary>
        private void ExecuteNonQuery()
        {
            StringBuilder cmd = new StringBuilder("Update ");
            cmd.Append(base.tableName);
            string column;

            while (this.parameters.Count > 0)
            {
                column = this.parameters.Dequeue();
                cmd.Append(" Set ")
                .Append(column)
                .Append("=")
                .Append("?")
                .Append(column);
                if (this.parameters.Count != 0)
                {
                    cmd.Append(',');
                }

            }
            this.AppendWhereStatments(cmd);
            if (this.limit != null)
            {
                cmd.Append(" Limit ").Append(this.limit);
            }

            cmd.Append(';');
            this.mySqlCommand.CommandText = cmd.ToString();
            using (this.mySqlCommand.Connection = MySqlCore.GetConnection())
            {
                this.mySqlCommand.ExecuteNonQuery();
            }
        }
    }
}
